package org.classg.ucenter.controller.api;

import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.classg.servicebase.exception.MyException;
import org.classg.ucenter.entity.Member;
import org.classg.ucenter.service.MemberService;
import org.classg.ucenter.utils.ConstantPropertiesUtil;
import org.classg.ucenter.utils.HttpClientUtils;
import org.classg.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@RequestMapping("/api/ucenter/wx")
@Controller
@Api(description = "微信登录系统")
public class WxApiController {

    @Autowired
    private MemberService memberService;

    @ApiOperation("生成微信扫描二维码")
    @GetMapping("/login")
    public String queryWxCode() {
        // 固定地址
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        // 对redirect_url进行URLEncode编码
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = String.format(baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "jiyue");
        return "redirect:" + url;
    }

    @ApiOperation("微信扫描二维码后的回调函数")
    @GetMapping("/callback")
    public String callback(String code, String state) {
        System.out.println("code:::" + code);
        System.out.println("state:::" + state);

        try {
            String baseUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String url = String.format(baseUrl,
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code);
            String resultTokeInfo = null;
            // 模拟浏览器得到的数据client，得到凭证和标识
            try {
                resultTokeInfo = HttpClientUtils.get(url);
            } catch (Exception e) {
                e.printStackTrace();
                throw new MyException(20001, "获取微信凭证失败！");
            }
            // 解析json（把json转化成map）
            Gson gson = new Gson();
            HashMap<String, Object> tokenInfoMap = gson.fromJson(resultTokeInfo, HashMap.class);
            String openid = (String) tokenInfoMap.get("openid");
            String accessToken = (String) tokenInfoMap.get("access_token");


            // 根据微信唯一标识openid来查询数据库
            Member member = memberService.queryUserByOpenId(openid);
            // 如果没有该用户，我们需要把信息查出来再添加
            if (member == null) {
                // 访问微信资源服务器，获取用户信息(使用httpclient发送请求，得到返回结果)
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?openid=%s" +
                        "&access_token=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, openid, accessToken);
                String resultUserInfo = null;
                // 模拟浏览器得到的数据client,得到用户的资料(使用httpclient发送请求，得到返回结果)
                try {
                    resultUserInfo = HttpClientUtils.get(userInfoUrl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new MyException(20001, "获取用户信息失败！");
                }
                // 解析json（把json转化成map）
                HashMap<String, Object> userInfoMap = gson.fromJson(resultUserInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");
                String headimgurl = (String) userInfoMap.get("headimgurl");

                // 没有该用户
                member = new Member();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }
            // 使用jwt根据member对象生成token字符串
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token=" + token;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(20001, "登录失败！");
        }
    }


}
